import json

import allure
import jsonpath
import pymysql
import requests

from config.config import *


class ApiKey():
    def __init__(self):
        self.env = config['dev'] # 手动指定环境
        self.base_url = self.env["base_url"] # 对应环境url前缀

    @allure.step("发送GET请求")
    def get(self, url, **kwargs):
        try:
            return requests.get(self.base_url + url, **kwargs)
        except requests.RequestException as e:
            print(f"发送GET请求失败：{e}")
            return None

    @allure.step("发送POST请求")
    def post(self, url, data=None, json=None, headers=None):
        try:
            return requests.post(self.base_url + url, data=data, json=json, headers=headers)
        except requests.RequestException as e:
            print(f"发送POST请求失败：{e}")
            return None

    @allure.step("获取指定响应信息")
    def get_post_response(self, response, json_path):
        res_dict = json.loads(response)
        res_value = jsonpath.jsonpath(res_dict, json_path)
        return res_value[0]  # 获取列表第一个值

    @allure.step("数据库检查")
    def check_sql(self, sql):
        # 1.数据库连接conn
        conn = pymysql.Connect(**self.env["db_config"])
        # 2.创建游标
        course = conn.cursor()
        # 3.准备执行sql
        course.execute(sql)
        # 4.查询数据
        sql_data = course.fetchone()
        # 5.关闭数据库
        conn.close()
        # 6.返回数据
        return sql_data[0]

    # 校验数据
    def assert_data(self, response, json_path, sign, expect):
        assert self.get_post_response(response, json_path) + sign + expect